package org.viva.core.exception;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
import org.viva.core.api.Ajax;

import net.sf.json.JSONObject;

public class CustomSimpleMappingExceptionResolver extends SimpleMappingExceptionResolver {

    @Override
    protected ModelAndView doResolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

        if (isAjax(request)) {
            try {
                response.setContentType("application/x-javascript;charset=UTF-8");
                PrintWriter writer = response.getWriter();
                writer.write(JSONObject.fromObject(Ajax.exec(false, ex.getMessage())).toString());
                writer.flush();
                ex.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
        String viewName = determineViewName(ex, request);
        if (viewName != null) {// JSP格式返回
            Integer statusCode = determineStatusCode(request, viewName);
            if (statusCode != null) {
                applyStatusCodeIfPossible(request, response, statusCode);
            }
            return getModelAndView(viewName, ex, request);
        } else {
            return null;
        }
    }

    public boolean isAjax(HttpServletRequest request) {
        if (request.getHeader("accept").indexOf("application/json") > -1
                || (request.getHeader("X-Requested-With") != null && request.getHeader("X-Requested-With").indexOf("XMLHttpRequest") > -1)) {
            return true;
        }
        return false;
    }
}